package com.gsnd.briuppts.web.Interceptor;

import com.gsnd.briuppts.Result.ResponseCode;
import com.gsnd.briuppts.Util.JwtUtil;
import com.gsnd.briuppts.entity.BaseAccount;
import com.gsnd.briuppts.exception.PtsException;
import com.gsnd.briuppts.mapper.BaseAccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Configuration
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    BaseAccountMapper baseAccountMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method=request.getMethod();
        if(method.equals("OPTIONS")){
            return true;
        }

        System.out.println("当前拦截的处理器是："+handler);
        String token=request.getHeader("token");
        if(token==null || "".equals(token)){
            throw new PtsException(ResponseCode.TOKEN_NOT_EXIST);
        }
        if(!JwtUtil.checkSign(token)){
            throw new PtsException(ResponseCode.TOKEN_INVALID);
        }
        // 4、验证token里保存的数据是否正确（可以不验证）
        String userId = JwtUtil.getUserId(token);
        String name = (String)JwtUtil.getInfo(token).get("username");



        // 4.1 取出id验证 通过id查询出来的用户是否存在

        // 根据id查询一个用户
        BaseAccount user = baseAccountMapper.getAccountById(userId);
        // 4.2 假设用户存在，和取出来的name进行比对看是否一致
        if(user == null){
            throw new PtsException(ResponseCode.DATA_VALIDATE_ERROR);
        }
        if(!user.getUsername().equals(name)){
            throw new PtsException(ResponseCode.DATA_VALIDATE_ERROR);
        }

        //将验证之后的id临时保存在会话中
        HttpSession session=request.getSession();
        session.setAttribute("userId",userId);


        return true;




    }
}
